package com.risk.kernel.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.stereotype.Component;

import java.sql.*;

/**
 * @author: Liwen
 * @createTime: 2024/11/25
 * @description:
 */

@Component
@Slf4j
public class GmfKeFuTestJdbcConfig {

    @Value("${datasource.kefu.host}")
    private String host;

    @Value("${datasource.kefu.port}")
    private String port;

    @Value("${datasource.kefu.username}")
    private String userName;

    @Value("${datasource.kefu.password}")
    private String password;


    private static Connection conn = null;
    private static PreparedStatement pst = null;
    private static Statement statement = null;

    public Connection getJdbcConn(String dbName) {
        String url = "jdbc:mysql://host:port/dbName?useSSL=false&serverTimezone=GMT%2B8&characterEncoding=utf-8";
        String jdbcUrl = url.replaceAll("host", host).replaceAll("port", port).replaceAll("dbName", dbName);
        String driverName = "com.mysql.jdbc.Driver";
        try {
            Class.forName(driverName);
            conn = DriverManager.getConnection(jdbcUrl, userName, password);

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public int execAction(String dbName, PreparedStatementCreator st) throws SQLException {
        getJdbcConn(dbName);
        pst = st.createPreparedStatement(conn);
        int count = 0;
        log.info("【执行的sql：{}】", pst.toString());
        count = pst.executeUpdate();
        if (count > 0) {
            log.info("【mysql 操作成功】===================================");
        }
        return count;
    }

    /**
     * 根据sql语句执行
     *
     * @param dbName
     * @param sql
     * @return
     * @throws SQLException
     */
    public int execAction(String dbName, String sql) throws SQLException {
        getJdbcConn(dbName);
        statement = conn.createStatement();
        int count = 0;
        count = statement.executeUpdate(sql);
        log.info("【执行的sql：{},count: {}】", sql, count);
        if (count > 0) {
            log.info("【mysql 操作成功】===================================");
        }
        return count;
    }

    /**
     * 关流
     */
    public void close() {
        if (conn != null) {
            try {
                if (pst != null) {
                    pst.close();
                }
                if (conn != null) {
                    conn.close();
                }
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
